from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from model.ModPendingProSupSta import PendingProSupSta, pendingProSupStaSchema
from model.ModBureauWeeklyRepSum import BureauWeeklyRepSum,bureauWeeklyRepSumSchema
from model.ModBureauMonRepSum import BureauMonRepSum,bureauMonRepSumSchema
from database import Session, engine
import datetime
from sqlalchemy.sql import text
from sqlalchemy import ARRAY
import pendulum
import logging

def get_read_check(session, bureauid: str, openid: str,flag: str):
    # 判断openid是否在read_flag字段中(1督办2周报3月报) 返回值:0未阅读1已阅读
    if flag == '1':
        info_list = session.query(PendingProSupSta).filter(PendingProSupSta.bureauid == bureauid).all()
        info = pendingProSupStaSchema.dump(info_list, many=True).data
        for i in info:
            dic = i.get("read_flag")
            if dic is None:
                return '0'
            else:
                cou = dic.count(openid)
                if cou < 1:
                    return '0'
        return "1"
    elif flag == '2':
        info_list = session.query(BureauWeeklyRepSum).filter(BureauWeeklyRepSum.bureauid == bureauid).all()
        info = bureauWeeklyRepSumSchema.dump(info_list, many=True).data
        for i in info:
            dic = i.get("read_flag")
            if dic is None:
                return '0'
            else:
                cou = dic.count(openid)
                if cou < 1:
                    return '0'
        return "1"
    elif flag == '3':
        info_list = session.query(BureauMonRepSum).filter(BureauMonRepSum.bureauid == bureauid).all()
        info = bureauMonRepSumSchema.dump(info_list, many=True).data
        for i in info:
            dic = i.get("read_flag")
            if dic is None:
                return '0'
            else:
                cou = dic.count(openid)
                if cou < 1:
                    return '0'
        return "1"
    else:
        return "3"

def update_read_flag(session, bureauid: str, openid: str, flag: str):
    # 更新阅读标志
    try:
        if flag == '1':
            txt1 = f'update "PendingProSupSta" set read_flag=array_append(read_flag,'
            txt2 = "'"
            txt3=f'where bureauid='
            txt=f'{txt1}{txt2}{openid}{txt2}){txt3}{txt2}{bureauid}{txt2}'
            session.execute(txt)
        elif flag == '2':
            print("pppppppppppp")
            txt1 = f'update "BureauWeeklyRepSum" set read_flag=array_append(read_flag,'
            txt2 = "'"
            txt3 = f'where bureauid='
            txt = f'{txt1}{txt2}{openid}{txt2}){txt3}{txt2}{bureauid}{txt2}'
            session.execute(txt)
        elif flag == '3':
            txt1 = f'update "BureauMonRepSum" set read_flag=array_append(read_flag,'
            txt2 = "'"
            txt3 = f'where bureauid='
            txt = f'{txt1}{txt2}{openid}{txt2}){txt3}{txt2}{bureauid}{txt2}'
            session.execute(txt)

    except Exception as e:
        raise
